package org.yn.auth.intercepter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yn.auth.annotation.PermissionAnnotation;
import org.yn.base.until.LoginContext;
import org.yn.emp.domain.Employee;
import org.yn.emp.service.IEmployeeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    IEmployeeService employeeService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器....");
        // 前端的token是放在header里面的
        String token = request.getHeader("token");
        System.out.println("前端传进的token："+token);
        if (StringUtils.isEmpty(token)){
            System.out.println("没有传入token");

            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;  //原本是false  为测试写为true
        }
        Employee user = (Employee)LoginContext.loginMap.get(token);
        if (Objects.isNull(user)){
            System.out.println("token取值错误");
            response.getWriter().print("{\"success\":false,\"msg\":\"NoLogin\"}");
            return false;//原本是false  为测试写为true
        }
        // 对于url路径的控制权限
        //1.判断用户访问的这个资源 是否需要权限

        HandlerMethod handlerMethod=(HandlerMethod)handler;
        PermissionAnnotation methodAnnotation = handlerMethod.getMethodAnnotation(PermissionAnnotation.class);
        if(Objects.nonNull(methodAnnotation)){  //如果这个方法上有这个注解
            //2.如果需要权限,判断用户是否有权限
            //2.首先拿到用户的权限 通过用户拿
           List<String> list=employeeService.queryPermissionByUserId(user.getId());

            System.out.println("用户的权限列表:");
            list.forEach(System.out::println);
            System.out.println("________________________");
            //2.2 再拿到当前资源的权限
            Method method = handlerMethod.getMethod();
            String mP=method.getDeclaringClass().getSimpleName()+":"+method.getName();
            System.out.println("mP:"+mP);
            //2.3比较用户的权限资源的权限 如果比对上就放行否则拦截
                if (!list.contains(mP)){
                    response.getWriter().print("{\"success\":false,\"msg\":\"NoPermission\"}");
                    System.out.println("没有权限访问！！");
                    return false;
                }

        }






        return true;
    }
}